<template>
  <a-layout id="xxl">
    <a-layout-sider
      breakpoint="lg"
      collapsed-width="0"
      @collapse="onCollapse"
      @breakpoint="onBreakpoint"
      theme="light"
      width="240"
      :style="{ overflowY: 'auto',overflowX: 'hidden', height: '100vh', left: 0 }"
      class="beauty-scroll"
    >
      <div class="company_name">
        <div class="left">
          <a-icon type="rollback" class="icon" title="返回账户管理" @click="goBack"/>
          <span>{{storeName}}</span>
        </div>
      </div>
      <a-skeleton :loading="loading" active :paragraph="{rows: 26}">
        <a-menu theme="light" mode="inline" style="background:#ffffff;" >
          <a-tree :expandedKeys.sync="expandedKeys" :tree-data="treeData" :replaceFields="{title:'campaignFeedName',key:'campaignFeedId'}" :load-data="onDanYanLoadData" @select="onSelect">
            <div slot="slot" class="line1" :class="item.mod=='danyuan'?'treeItem2':'treeItem'" slot-scope="item" @click="treeClick(item)">
              <a-tooltip placement="top">
                <template slot="title">
                  <span v-if="item.mod == 'home'">{{item.campaignFeedName}}</span>
                  <span v-if="item.mod == 'jihua'">{{item.campaignFeedName}}</span>
                  <span v-if="item.mod == 'danyuan'">{{item.adgroupFeedName}}</span>
                </template>
                <span v-if="item.mod == 'home'">{{item.campaignFeedName}}</span>
                <span v-if="item.mod == 'jihua'">{{item.campaignFeedName}}</span>
                <span v-if="item.mod == 'danyuan'">{{item.adgroupFeedName}}</span>
              </a-tooltip>
            </div>
          </a-tree>
        </a-menu>
      </a-skeleton>
    </a-layout-sider>
    <a-layout class="content beauty-scroll">
      <a-layout-content :style="{ margin: '24px 16px',height:'100vh',boxSizing: 'border-box' }">
        <div :style="{ height: '100%', display:'flex',flexDirection: 'column',}">
          <info :balance='dianpuInfo.balance' :budget="dianpuInfo.budget" :userStat='dianpuInfo.userStat' :userId="dianpuInfo.userId" @refresh="getAccountFeed"/>
          <!-- 计划start -->
          <div style="margin-top:16px;background-color:#ffffff;border-radius: 6px;padding:20px" v-if="current == 0">
            <a-space class="operator" style="margin-bottom:20px;">
              <!-- <a-button @click="goBatch" type="primary">批量创意</a-button> -->
              <a-popconfirm title="批量基木鱼还是直播？" ok-text="基木鱼" cancel-text="直播" @cancel="oneClickZhibo" @confirm='oneClickCreate' >
                <a-button type="primary">一键添加</a-button>
              </a-popconfirm>
              <a-button @click="add" type="primary">批量创意</a-button>
              <!-- <a-button @click="addChengxuhua" type="primary">批量程序化</a-button> -->
              <bulkJHDY @confirm="getAccountFeed" />
              <bulkZhibo @confirm="getAccountFeed" />
              <a-button @click="copyBengdi">复制到本账户</a-button>
              <a-button @click="copy('jihua')">复制计划</a-button>
              <a-button @click="copy('sucai')">复制素材</a-button>
              <a-popconfirm  title="确定删除？" ok-text="删除" cancel-text="取消" @confirm='delAll'>
                <a-button :disabled="selectedRowsForId.length == 0" type="danger">删除</a-button>
              </a-popconfirm>
            </a-space>
            <standard-table
              showAlert
              :loading='loading'
              :columns="columns"
              :dataSource="dataSource"
              :selectedRows.sync="selectedRowKeys"
              :pagination="{showTotal:total => `共 ${total} 个计划`}"
              @selectedRowChange="selectedRowChange"
              @clear="onClear"
              @change="onChange"
              :scroll="{x:1200}"
            >
              <div slot="campaignFeedName" slot-scope="{record}">
                <span style="">{{record.campaignFeedName}}</span>
              </div>
              <div slot="status" slot-scope="{record}">
                <div style="display:flex;align-items: center;">
                  <div style="width:6px;height:6px;border-radius:50%;background-color:#00cc63" v-if="record.status==0"></div>
                  <div style="width:6px;height:6px;border-radius:50%;background-color:#ff7875" v-else></div>
                  <span style="margin-left:5px">{{record.status | setStatus}}</span>
                </div>
              </div>
              <div slot="subject" slot-scope="{record}">
                <div style="display:flex;align-items: center;">
                  <span style="margin-left:5px">{{record.subject | setSubject}}</span>
                </div>
              </div>
              <div slot="addtime" slot-scope="{record}">
                {{moment(new Date(record.addtime).valueOf()).format("YYYY-MM-DD HH:mm:ss")}}
              </div>
              <div slot="action" slot-scope="{record}" >
                <a-popconfirm title="确定操作？" ok-text="确定" cancel-text="取消" @confirm='updatePause(1, record.campaignFeedId)' v-if="!record.pause">
                  <a href="javascript:;" style="margin-right: 8px" >
                    <a-icon type="edit"/>暂停推广
                  </a>
                </a-popconfirm>
                <a-popconfirm title="确定操作？" ok-text="确定" cancel-text="取消" @confirm='updatePause(0, record.campaignFeedId)' v-else>
                  <a href="javascript:;" style="margin-right: 8px" >
                  <a-icon type="edit"/>开启推广
                </a>
                </a-popconfirm>
                <a-popconfirm title="确定删除？" ok-text="删除" cancel-text="取消" @confirm='deleteRecord(record.campaignFeedId)'>
                  <a href="javascript:;">
                    <a-icon type="delete" />删除
                  </a>
                </a-popconfirm>
              </div>
            </standard-table>
          </div>
          <!-- 选择需复制的账号 -->
          <a-modal v-model="showChooseZhanghu" title="选择目标账号" :width="600" okText="复制" @ok="fuzhi" :confirm-loading="fuzhiLoading">
            <a-input-search placeholder="搜索目标账号" enter-button @search="onFuzhiSearch" style="margin-bottom:20px;" />
            <a-checkbox-group @change="onZhanghaoChange" style="width: 100%;max-height: 600px;overflow-y: auto;">
              <a-row>
                <a-col :span="8" v-for="(item,index) in zhanghaoId" :key="index">
                  <!-- <a-checkbox :value="item.id" v-if="item.name == storeName" style="color:#1890ff;">{{item.name}}(本账户)</a-checkbox> -->
                  <a-checkbox :value="item.id" v-if="item.name != storeName">{{item.name}}</a-checkbox>
                </a-col>
              </a-row>
            </a-checkbox-group>
          </a-modal>
          <a-modal v-model="showFuzhiZhanghu" title="选择复制信息" :width="600" okText="复制" @ok="fuzhiBendi" :confirm-loading="fuzhiLoading">
            <a-form-model ref="ruleForm" :model="fuzhiForm" :rules="fuzhiRules" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-form-model-item label="复制次数" >
                <a-input-number v-model="fuzhiForm.amount" :min="1" />
              </a-form-model-item>
              <a-form-model-item label="价格区间" >
                <div style="display:flex;align-items:center;">
                  <a-input-number v-model="fuzhiForm.start_price" :min="0" />
                  <div style="padding:0 10px;">-</div>
                  <a-input-number v-model="fuzhiForm.end_price" :min="0" />
                </div>
              </a-form-model-item>
            </a-form-model>
          </a-modal>
          <!-- 选择需复制的账号 -->
          <!-- 计划end -->
          <!-- 单元start -->
          <danyuanView :campaignFeedId='campaignFeedId' v-if="current==1"/>
          <!-- 单元end -->
          <!-- 创意start -->
          <chuangyiView :adgroupFeedId='adgroupFeedId' v-if="current==2"/>
          <!-- 创意end -->
        </div> 
      </a-layout-content>
    </a-layout>
  </a-layout>
</template>
<script>
import StandardTable from '@/components/table/StandardTable'
import { getAccountFeed } from '@/api/xinxiliu/xinxiliu'
import { batchCampaign,batchUpload,copyToSelf,updateCampaignFeed } from '@/api/xinxiliu/getBaidu'
import { getCampaignFeed,deleteCampaignFeed } from '@/api/xinxiliu/jihua'
import { getAdgroupFeed } from '@/api/xinxiliu/danyuan'
import { getBdAccountList } from '@/api/xinxiliu/account'
import danyuanView from './danyuan'
import chuangyiView from './chuangyi'
import bulkJHDY from './bulkJHDY'
import bulkZhibo from './bulkZhibo'
import moment from 'moment'
import info from './components/info.vue'

// const dataSource = [
//   {id:1,name:'3.10通投ocpc默认（即优选）',status:1,target:'电商店铺',zhanxian:0,dianji:0,xiaofei:0,dianjilv:'100%',averageClickPrice:998,thousandPrice:8848}
// ]

export default {
  name:'xinxiliu',
  data() {
    return {
      moment,
      selectedRowKeys:[],
      selectedRowsForId:[], //搬迁功能的id
      zhanghaoId:[],
      zhanghaoIdToatal:[],
      toZhanghaoId:[],
      showChooseZhanghu:false,
      showFuzhiZhanghu:false,
      fuzhiLoading:false,
      fuzhiType:'',
      labelCol: { span: 3 },
      wrapperCol: { span: 8 },
      fuzhiForm:{ // 复制本账户的选项
        amount:1,
        sourceCampaignId:'',
        start_price:0,
        end_price:0
      }, 
      fuzhiRules:{
        
      },
      dianpuInfo:{}, //账户信息
      current:0, //0：计划，1：单元，2：创意
      campaignFeedId:'', //计划id,传给单元组件调用单元列表
      adgroupFeedId:'', //单元id,传给创意组件调用创意列表

      expandedKeys:[],
      treeData:[],
      dataSource:[],
      selectedRows:[],
      loading:false,
      page:1,
      limit:10,
      count:1,
      total:0,
      columns:[
        {
          title: '推广计划',
          fixed:'left',
          dataIndex: 'campaignFeedName',
          // defaultSortOrder: 'descend',
          scopedSlots: { customRender: 'campaignFeedName' },
          with: 500,
          sorter: (a, b) => new Date(a.addtime).valueOf() - new Date(b.addtime).valueOf(),
        },
        {
          title: '状态',
          width:160,
          dataIndex: 'status',
          scopedSlots: { customRender: 'status' }
        },
        {
          title: '营销目标',
          width:200,
          dataIndex: 'subject',
          scopedSlots: { customRender: 'subject' }
        },
        {
          title: '添加时间',
          width:250,
          dataIndex: 'addtime',
          scopedSlots: { customRender: 'addtime' }
        },
        {
          title: '操作',
          fixed:'right',
          width:200,
          scopedSlots: { customRender: 'action' }
        },
        // {
        //   title: '点击',
        //   dataIndex: 'dianji',
        // },
        // {
        //   title: '消费',
        //   dataIndex: 'xiaofei',
        // },
        // {
        //   title: '点击率',
        //   dataIndex: 'dianjilv',
        // },
        // {
        //   title: '平均点击价格',
        //   dataIndex: 'averageClickPrice',
        // },
        // {
        //   title: '千次展现消费',
        //   dataIndex: 'thousandPrice',
        // },
      ]
    }
  },
  created(){
    this.getAccountFeed()
  },
  methods: {
    getAccountFeed(){ //查询账户信息
      const _this = this;
      this.loading = true
      getAccountFeed({}).then(e=>{
        if(e.errcode == 0){
          _this.dianpuInfo = e.data.body.data[0]
          _this.getCampaignFeed()
        }
      })
    },
    getCampaignFeed(){ //查询计划
      const _this = this;
      let params = {
        pageSize:50
      }
      getCampaignFeed(params).then(e=>{
        if(e.errcode == 0){
          let key = 1;
          let ids = []; //带查询计划id,用于查询计划下的单元
          for(let i of e.data.body.data){
            i.key = key;
            i.scopedSlots = {title: 'slot'}
            ids.push(i.campaignFeedId)
            i.mod = 'jihua'
            key++;
          }
          e.data.body.data = e.data.body.data.sort((a, b) => new Date(b.addtime).valueOf() - new Date(a.addtime).valueOf())
          let dataSource = JSON.parse(JSON.stringify(e.data.body.data))
          let children = e.data.body.data
          // console.log('dataSource',dataSource)
          _this.dataSource = dataSource
          _this.total = dataSource.length
          let treeData = [
            {campaignFeedName:'电商店铺',key:'0',campaignFeedId:'0',mod:'home',scopedSlots:{title: 'slot'},children}
          ]
          _this.loading = false
          _this.treeData = treeData
          _this.$nextTick(()=>{
            _this.expandedKeys = ['0']
          })
        }else{
          _this.loading = false
        }
      }).catch(()=>{
        _this.loading = false
      })
    },
    onDanYanLoadData(treeNode){
      return new Promise(resolve => {
        if (treeNode.dataRef.children) {
          resolve();
          return;
        }
        let params = {
          ids: [treeNode.eventKey],
          idType:1 
        }
        getAdgroupFeed(params).then((e) => {
          if(e.errcode == 0){
            let data = e.data.body.data
            for(let i of data){
              i.scopedSlots = {title: 'slot'}
              i.mod = 'danyuan'
            }
            treeNode.dataRef.children = data
            this.treeData = [...this.treeData]
          }
          resolve()
        }).catch(()=>{
          resolve()
        });
      })
    },
    getDanyuan(ids,children){ //查询计划下的单元，并拼接成树型数据
      const _this = this;
      let params = {
        ids,
        idType:1 // 1 - 计划类型 2 - 单元类型
      }
      getAdgroupFeed(params).then((e) => {
        this.loading = false
        if(e.errcode == 0){
          let data = e.data.body.data
          for(let i of data){
            i.scopedSlots = {title: 'slot'}
            i.mod = 'danyuan'
          }
          for(let item of children){
            item.children = data.filter(e=>e.campaignFeedId == item.campaignFeedId)
          }
          let treeData = [
            {campaignFeedName:'电商店铺',key:'0',campaignFeedId:0,mod:'home',scopedSlots:{title: 'slot'},children}
          ]
          _this.treeData = treeData
          _this.expandedKeys = ['0']
        }
      });
    },
    copyBengdi(){
      let selectedRowsForId = this.selectedRowsForId
      if(selectedRowsForId.length == 1){
        this.showFuzhiZhanghu = true
      }else{
        this.$message.error('请选择一个计划复制到本地')
      }
    },
    updatePause(pause, campaignFeedId){
      this.loading = true
      updateCampaignFeed({pause, campaignFeedId}).then((res) => {
        if(res.errcode == 0){
          this.$message.success('修改成功')
          this.getCampaignFeed()
        }else{
          this.loading = false
        }
      }).catch(() => {
        this.loading = false
      });
    },
    copy(type){
      let selectedRowsForId = this.selectedRowsForId
      this.fuzhiType = type
      if(selectedRowsForId.length > 0){
        this.showChooseZhanghu = true
        getBdAccountList({}).then((res) => {
          console.log(res)
          if(res.errcode == 0){
            let data = res.data.filter(e=>e.pid > 0)
            let zhanghaoId = data.map(e=>{
              return {
                name:e.account,
                id:e.id
              }
            })
            this.zhanghaoId = zhanghaoId
            this.zhanghaoIdToatal = zhanghaoId
          }
        });
      }else{
        this.$message.error('请选择需要复制的计划')
      }
    },
    fuzhiBendi(){
      this.fuzhiForm.sourceCampaignId = this.selectedRowsForId[0]
      console.log(this.fuzhiForm)
      this.fuzhiLoading = true
      copyToSelf(this.fuzhiForm).then((res) => {
        this.fuzhiLoading = false
        if(res.errcode == 0){
          this.showFuzhiZhanghu = false
          this.$message.success('复制成功')
          this.getAccountFeed()
        }
      }).catch(() => {
        this.fuzhiLoading = false
      });
    },
    fuzhi(){
      let sourceCampaignIds = this.selectedRowsForId.join(',')
      let destAccountIds = this.toZhanghaoId.join(',')
      this.fuzhiLoading = true
      console.log(sourceCampaignIds,destAccountIds)
      let params = {
        sourceCampaignIds,
        destAccountIds
      }
      if(this.fuzhiType == 'jihua'){
        batchCampaign(params).then((res) => {
          this.fuzhiLoading = false
          if(res.errcode == 0){
            this.showChooseZhanghu = false
            this.$message.success('复制成功')
          }
        }).catch(()=>{
          this.fuzhiLoading = false
        });
      }else if(this.fuzhiType == 'sucai'){
        batchUpload(params).then((res) => {
          this.fuzhiLoading = false
          if(res.errcode == 0){
            this.showChooseZhanghu = false
            this.$message.success('复制成功')
          }
        }).catch(()=>{
          this.fuzhiLoading = false
        });
      }
    },
    deleteRecord(campaignFeedIds){
      const _this = this;
      const hideLoding = _this.$message.loading('删除中')
      deleteCampaignFeed({campaignFeedIds}).then((e) => {
        hideLoding()
        if(e.errcode == 0){
          _this.$message.success('删除成功')
          _this.getAccountFeed()
        }
      }).catch(()=>{
        hideLoding()
      });
    },
    delAll(){
      const _this = this;
      let campaignFeedIds = this.selectedRowsForId.join()
      const hideLoding = _this.$message.loading('删除中')
      deleteCampaignFeed({campaignFeedIds}).then((e) => {
        hideLoding()
        if(e.errcode == 0){
          _this.selectedRowsForId = []
          _this.selectedRowKeys = []
          _this.$message.success('删除成功')
          _this.getAccountFeed()
        }
      }).catch(()=>{
        hideLoding()
      });
    },
    treeClick(item){
      console.log(item)
      switch(item.mod){
        case 'home':
          this.current = 0
          this.campaignFeedId = 0 //计划id
          this.adgroupFeedId = 0 //单元id
          // this.$router.push('/xinxiliu/bulkAdd?campaignFeedId='+item.campaignFeedId+'&adgroupFeedId='+item.adgroupFeedId)
          break
        case 'jihua':
          this.current = 1
          this.campaignFeedId = item.campaignFeedId
          break
        case 'danyuan':
          this.current = 2
          this.campaignFeedId = item.campaignFeedId //计划id
          this.adgroupFeedId = item.adgroupFeedId //单元id
          // this.$router.push('/xinxiliu/bulkAdd?campaignFeedId='+item.campaignFeedId+'&adgroupFeedId='+item.adgroupFeedId)
          break
      }
    },
    onSelect(selectedKeys, info) {
      console.log('selected', selectedKeys, info);
    },
    goBatch(){
      this.$router.push('/xinxiliu/batchCreativity')
    },
    add(){
      this.$router.push('/xinxiliu/bulkAdd')
      // this.$router.push('/xinxiliu/add/step1')
    },
    oneClickCreate(){
      this.$router.push('/xinxiliu/batch')
    },
    oneClickZhibo(){
      this.$router.push('/xinxiliu/batchzhibo')
    },
    addChengxuhua(){
      this.$router.push('/xinxiliu/chengxuhuaAdd')
    },
    onCollapse(collapsed, type) {
      console.log(collapsed, type);
    },
    onBreakpoint(broken) {
      console.log(broken);
    },
    goBack(){
      this.$router.push(process.env.VUE_APP_HOME_PATH)
    },
    selectedRowChange(selectedRowKeys, selectedRows){
      console.log('selectedRowChange',selectedRowKeys, selectedRows)
      this.selectedRowsForId = selectedRows.map(e=>e.campaignFeedId)
    },
    onZhanghaoChange(e){
      this.toZhanghaoId = e
    },
    onFuzhiSearch(e){
      let zhanghaoIdToatal = JSON.parse(JSON.stringify(this.zhanghaoIdToatal))
      if(e != ""){
        this.zhanghaoId = zhanghaoIdToatal.filter(o=>o.name.indexOf(e) != -1)
      }else{
        this.zhanghaoId = zhanghaoIdToatal
      }
      console.log(e)
    },
    onChange(e){
      console.log('onChange',e)
    },
    onClear(e){
      console.log('onClear',e)
    },
  },
  filters:{
    setStatus(e){
      switch(e){
        case 0: case '0':
          return '有效'
        case 1: case '1':
          return '处于暂停时段'
        case 2: case '2':
          return '暂停推广'
        case 3: case '3':
          return '推广计划预算不足'
        case 4: case '4':
          return '账户待激活'
        case 11: case '11':
          return '账户预算不足'
        case 20: case '20':
          return '账户余额为零'
        case 23: case '23':
          return '被禁推'
        case 24: case '24':
          return 'app已下线'
        case 25: case '25':
          return '应用审核中'
      }
    },
    setSubject(e){
      switch(e){
        case 1: case '1':
          return '网站链接'
        case 2: case '2':
          return '应用下载（IOS）'
        case 3: case '3':
          return '应用下载（Android）'
        case 7: case '7':
          return '电商店铺'
      }
    }
  },
  computed:{
    storeName(){
      return this.$store.state.dianpu.name
    }
  },
  components:{
    info,
    StandardTable,
    danyuanView,
    chuangyiView,
    bulkJHDY,
    bulkZhibo,
  }
};
</script>

<style lang="less" scoped>
.line1{
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
#xxl {
  height: 100vh;
  .treeItem{
    width: 155px;
    // margin-left: -10px;
  }
  .treeItem2{
    width: 135px;
    // margin-left: -10px;
  }
  .company_name{
    .left{
      display: flex;
      align-items: center;
      .icon{
        cursor: pointer;
      }
      span{
        font-size: 14px;
        font-weight: 500;
        color: #282c33;
        margin-left: 8px;
      }
    }
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: 1px solid #ebedf5;
    background-color: #ffffff;
    padding: 0 16px
  }

  .content{
    height: 100vh;
  }
  /deep/ .ant-skeleton-active{
    padding: 0 20px;
  }
}
</style>
